"""
预测服务模块 - 连接前端和模型预测功能
"""
import os
import json
import time
from model.one_predict import predict_single_eye
from model.two_predict import predict_both_eyes

class PredictService:
    """预测服务类，处理眼底图像分析请求"""
    
    def __init__(self, upload_folder="uploads"):
        """
        初始化预测服务
        
        参数:
            upload_folder: 上传文件存储的文件夹路径
        """
        self.upload_folder = upload_folder
        print(f"预测服务初始化，上传文件夹: {upload_folder}")
        
    def predict(self, mode, patient_info, image_files=None):
        """
        执行预测分析
        
        参数:
            mode: 预测模式，'single'表示单眼，'both'表示双眼
            patient_info: 患者信息字典
            image_files: 图像文件信息，单眼模式下为单个文件名，双眼模式下为包含left和right键的字典
            
        返回:
            包含预测结果的字典
        """
        try:
            print(f"\n{'='*50}")
            print(f"开始预测 - 模式: {mode}")
            print(f"患者信息: {patient_info}")
            print(f"图像文件: {image_files}")
            
            # 验证输入
            if not mode or not patient_info:
                print("错误: 缺少必要参数")
                return {"success": False, "message": "缺少必要参数"}
                
            if not image_files:
                print("错误: 未提供图像文件")
                return {"success": False, "message": "未提供图像文件"}
            
            # 根据模式执行不同的预测
            if mode == 'single':
                print("执行单眼预测...")
                # 单眼预测
                if isinstance(image_files, str):
                    # 构建完整的图像路径
                    image_path = os.path.join(self.upload_folder, image_files)
                    print(f"单眼图像路径: {image_path}")
                    
                    # 检查文件是否存在
                    if not os.path.exists(image_path):
                        print(f"错误: 图像文件不存在: {image_path}")
                        return {"success": False, "message": f"图像文件不存在: {image_files}"}
                    
                    print("文件存在，开始调用单眼预测函数...")
                    start_time = time.time()
                    
                    # 调用单眼预测函数
                    prediction_result = predict_single_eye(image_path)
                    
                    end_time = time.time()
                    print(f"预测完成，耗时: {end_time - start_time:.2f}秒")
                    
                    # 检查是否有错误
                    if "error" in prediction_result:
                        print(f"预测失败: {prediction_result['error']}")
                        return {"success": False, "message": f"预测失败: {prediction_result['error']}"}
                    
                    print(f"预测结果: {prediction_result['diagnosis']}")
                    
                    # 获取置信度最高的类别
                    max_class = max(prediction_result["probabilities"].items(), key=lambda x: x[1])
                    predicted_class = max_class[0]
                    confidence = max_class[1]
                    
                    # 构建匹配前端期望格式的结果
                    result = {
                        "success": True,
                        "mode": "single",
                        "batch": False,
                        "patient_info": patient_info,
                        "diagnosis": {
                            "predicted_class": predicted_class,
                            "confidence": confidence,
                            "class_probabilities": prediction_result["probabilities"]
                        }
                    }
                    
                    print("预测成功，返回结果")
                    return result
                else:
                    print("错误: 单眼模式下图像文件格式不正确")
                    return {"success": False, "message": "单眼模式下图像文件格式不正确"}
                    
            elif mode == 'both':
                print("执行双眼预测...")
                # 双眼预测
                if isinstance(image_files, dict) and 'left' in image_files and 'right' in image_files:
                    # 构建完整的图像路径
                    left_image_path = os.path.join(self.upload_folder, image_files['left'])
                    right_image_path = os.path.join(self.upload_folder, image_files['right'])
                    
                    print(f"左眼图像路径: {left_image_path}")
                    print(f"右眼图像路径: {right_image_path}")
                    
                    # 检查文件是否存在
                    if not os.path.exists(left_image_path):
                        print(f"错误: 左眼图像文件不存在: {left_image_path}")
                        return {"success": False, "message": f"左眼图像文件不存在: {image_files['left']}"}
                    if not os.path.exists(right_image_path):
                        print(f"错误: 右眼图像文件不存在: {right_image_path}")
                        return {"success": False, "message": f"右眼图像文件不存在: {image_files['right']}"}
                    
                    print("文件存在，开始调用双眼预测函数...")
                    start_time = time.time()
                    
                    # 调用双眼预测函数
                    prediction_result = predict_both_eyes(left_image_path, right_image_path)
                    
                    end_time = time.time()
                    print(f"预测完成，耗时: {end_time - start_time:.2f}秒")
                    
                    # 检查是否有错误
                    if "error" in prediction_result:
                        print(f"预测失败: {prediction_result['error']}")
                        return {"success": False, "message": f"预测失败: {prediction_result['error']}"}
                    
                    print(f"预测结果: {prediction_result['diagnosis']}")
                    
                    # 获取置信度最高的类别
                    max_class = max(prediction_result["probabilities"].items(), key=lambda x: x[1])
                    predicted_class = max_class[0]
                    confidence = max_class[1]
                    
                    # 构建匹配前端期望格式的结果
                    result = {
                        "success": True,
                        "mode": "both",
                        "batch": False,
                        "patient_info": patient_info,
                        "diagnosis": {
                            "predicted_class": predicted_class,
                            "confidence": confidence,
                            "class_probabilities": prediction_result["probabilities"]
                        }
                    }
                    
                    print("预测成功，返回结果")
                    return result
                else:
                    print("错误: 双眼模式下图像文件格式不正确")
                    return {"success": False, "message": "双眼模式下图像文件格式不正确"}
            else:
                print(f"错误: 不支持的预测模式: {mode}")
                return {"success": False, "message": f"不支持的预测模式: {mode}"}
                
        except Exception as e:
            import traceback
            print(f"预测过程中发生错误: {str(e)}")
            print(traceback.format_exc())
            return {"success": False, "message": f"预测过程中发生错误: {str(e)}"}
        finally:
            print(f"{'='*50}\n")

# 创建预测服务实例
predict_service = PredictService()
